﻿using System.Collections.Generic;
using System.Linq;
using System.Management;

namespace HardwareUtils
{
    public class PnPDevices
    {
        public static List<PnPDeviceInfo> GetDevices (string property, string value)
        {
            ManagementObjectCollection collection;
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(string.Format(@"Select * From Win32_PnPEntity where {0}='{1}'", property, value)))
            {
                collection = searcher.Get();
            }

            var devices = collection.Cast<ManagementObject>()
                .Select(device => new PnPDeviceInfo(
                                      device.Path.ToString(),
                                      (string) device.GetPropertyValue("DeviceID"),
                                      (string) device.GetPropertyValue("PNPDeviceID"),
                                      (string) device.GetPropertyValue("Name")))
                .ToList();

            collection.Dispose();
            return devices;
        }

        public static List<PnPDeviceInfo> GetPorts ()
        {
            ManagementObjectCollection collection;
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(@"Select * From Win32_SerialPort"))
            {
                collection = searcher.Get();
            }

            var devices = collection.Cast<ManagementObject>()
                .Select(device => new PnPDeviceInfo(
                                      device.Path.ToString(),
                                      (string) device.GetPropertyValue("DeviceID"),
                                      (string) device.GetPropertyValue("PNPDeviceID"),
                                      (string) device.GetPropertyValue("Name"))).ToList();

            collection.Dispose();
            return devices;
        }

        #region Nested type: PnPDeviceInfo
        public class PnPDeviceInfo
        {
            public PnPDeviceInfo (string path, string deviceID, string pnpDeviceID, string description)
            {
                this.Path = path;
                this.DeviceID = deviceID;
                this.PnpDeviceID = pnpDeviceID;
                this.Description = description;
            }

            public string Path { get; private set; }
            public string DeviceID { get; private set; }
            public string PnpDeviceID { get; private set; }
            public string Description { get; private set; }
        }
        #endregion
    }
}